package com.blue.common.utils;

import cn.hutool.core.util.StrUtil;
import com.blue.common.constant.CommonConstant;
import com.blue.common.entity.Relation;
import com.blue.common.exception.CustomException;
import com.github.yulichang.query.MPJQueryWrapper;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;

/**
 * @author nanjie.chen
 * Created on 2022/11/19
 */
public class QueryWrapperUtils<T> {
    //自动组装查询条件
    public static <T> MPJQueryWrapper<T> initQueryWrapper(T t, String select, String order, String orderType, Relation... relations) {
        MPJQueryWrapper<T> queryWrapper = new MPJQueryWrapper<>();
        //关联副表
        if (relations != null) {
            for (int i = 0; i < relations.length; i++) {
                String[] fields = relations[i].getField().split(",");
                for (int j = 0; j < fields.length; j++) {
                    fields[j] = "t" + (i + 1) + "." + fields[j];
                }
                queryWrapper.select(fields);
                queryWrapper.leftJoin(relations[i].getAssociationConditions());
            }
        }
        //组装主表查询条件
        if (StringUtils.isNotBlank(select)) {
            queryWrapper.select(select);
        } else {
            queryWrapper.select("t.*");
        }
        //通过反射获取T对象中非空的字段和值
        Class<?> aClass = t.getClass();
        Field[] fields = aClass.getDeclaredFields();
        boolean hasIsFlag = false;
        boolean hasOrderField = false;
        for (Field field : fields) {
            switch (field.getName()) {
                //过滤掉UID
                case "serialVersionUID" -> {
                    continue;
                }
                //数据有效标识
                case "isFlag" -> hasIsFlag = true;
                //数据排序字段
                case "createTime" -> hasOrderField = true;
            }
            try {
                field.setAccessible(true);
                Object value = field.get(t);
                //当值不为空就拼接条件
                if (value instanceof String ? StringUtils.isNoneBlank(String.valueOf(value)) : value != null) {
                    String fieldName = "t." + StrUtil.toUnderlineCase(field.getName());
                    if (value instanceof String) {
                        String strValue = String.valueOf(value);
                        //参数含有*就模糊查询
                        if (strValue.startsWith("*") && strValue.endsWith("*")) {
                            queryWrapper.like(fieldName, strValue.replace("*", ""));
                        } else if (strValue.startsWith("*")) {
                            queryWrapper.likeLeft(fieldName, strValue.replace("*", ""));
                        } else if (strValue.endsWith("*")) {
                            queryWrapper.likeRight(fieldName, strValue.replace("*", ""));
                        } else if (strValue.endsWith("!")) {
                            queryWrapper.ne(fieldName, strValue.replace("!", ""));
                        } else {
                            queryWrapper.eq(fieldName, strValue);
                        }
                    } else {
                        queryWrapper.eq(fieldName, value);
                    }
                }
            } catch (Exception e) {
                throw new CustomException("查询条件组装失败!");
            }
        }
        //添加数据有效条件
        if (hasIsFlag) {
            queryWrapper.eq("t.is_flag", CommonConstant.YES);
        }
        //排序
        if (StringUtils.isNotBlank(order)) {
            //0-升序，1-降序
            if (StringUtils.isNotBlank(orderType)) {
                if (CommonConstant.ASC.equals(orderType)) {
                    queryWrapper.orderByAsc(order);
                } else if (CommonConstant.DESC.equals(orderType)) {
                    queryWrapper.orderByDesc(order);
                }
            } else {
                //未指定默认降序
                queryWrapper.orderByDesc(order);
            }
        } else if (hasOrderField) {
            queryWrapper.orderByDesc("t.create_time");
        }
        return queryWrapper;
    }

    public static <T> MPJQueryWrapper<T> initQueryWrapper(T t) {
        return initQueryWrapper(t, null, null, null);
    }

    public static <T> MPJQueryWrapper<T> initQueryWrapper(T t, String select) {
        return initQueryWrapper(t, select, null, null);
    }

    public static <T> MPJQueryWrapper<T> initQueryWrapper(T t, String order, String orderType) {
        return initQueryWrapper(t, null, order, orderType);
    }

    public static <T> MPJQueryWrapper<T> initQueryWrapper(T t, String select, String order, String orderType) {
        return initQueryWrapper(t, select, order, orderType, null);
    }

    public static <T> MPJQueryWrapper<T> initQueryWrapper(T t, Relation... relations) {
        return initQueryWrapper(t, null, null, null, relations);
    }

    public static <T> MPJQueryWrapper<T> initQueryWrapper(T t, String order, Relation... relations) {
        return initQueryWrapper(t, null, order, null, relations);
    }
}
